<template>
  <el-breadcrumb class="breadcrumb" separator="/">
    <!-- transition-group动画 transition.scss-->
    <transition-group name="breadcrumb">
      <el-breadcrumb-item
        v-for="(item, index) in breadcrumbData"
        :key="item.path"
      >
        <!-- 最后一项，不可点击路径 -->
        <span v-if="index === breadcrumbData?.length - 1" class="no-redirect">
          {{ item.meta.title }}
        </span>
        <span v-else class="redirect" @click.prevent="handleClick(item)">
          {{ item.meta.title }}
        </span>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

// 生成数组数据
const route = useRoute()
const breadcrumbData = ref([])
const getBreadcrumbData = () => {
  // https://router.vuejs.org/zh/api/interfaces/RouteLocationNormalizedLoaded.html
  // route.matched获取与给定路由地址匹配的标准化的路由 记录数组
  console.log('route.matched', route.matched)
  breadcrumbData.value = route.matched.filter((i) => i.meta && i.meta.title) // 仅取title
  console.log('breadcrumbData.value', breadcrumbData.value)
}

// 监听路由变化触发
watch(
  route,
  () => {
    getBreadcrumbData()
  },
  { immediate: true } // 创建侦听器时，立即执行一遍回调
)

// 处理点击事件
const router = useRouter()
const handleClick = (item) => {
  router.push(item.path)
}
</script>
<style scoped lang="scss">
.breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;

  ::v-deep .no-redirect {
    color: #97a8be;
    cursor: text;
  }
}
</style>
